package com.OnTimeTeam.OnTime;

import java.io.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
import org.w3c.dom.*;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;


/***********************************************************************************************************
 * @author Daniel huri

 * Class: RemindersIO
 * Parsing Method: DOM
 * File-name we write to: "reminders.xml" - In this file we'll find all the alarms that were set by the user.
 * NOTICE: This method is used as static method (can't be instantiated to an object)
 * More: This class is responsible for all the IO into/from mobile SD card.
 ***********************************************************************************************************/
public class RemindersIO {

	////////////////
	//Creates the file "reminders.xml" if doesn't exists - this method is activated in the very beginning of the application
	public static void createRemindersXMLFile(String filePath) {
		
		//initializeRemindersFile(filePath);

        try {

        	//filePath paramether - the path of the file (on mobile it's SD card)
            
    		//create file object in the path given
    		File file = new File(filePath);
        	
    		//Only if file doesn't exist - create the reminders.xml file and enter the reminders node
    		if(file.createNewFile()) {
    			
	        	//Creating an empty XML Document
	
	        	//We need a Document
	        	DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
	        	DocumentBuilder docBuilder = dbFactory.newDocumentBuilder();
	            Document doc = docBuilder.newDocument();
	
	            ////////////////////////
	            //Creating the XML tree
	            
	            doc.normalize();
	
	            //create the root element named Reminders and add it to the document
	            Element root = doc.createElement("reminders");
	            doc.appendChild(root);

	            /////////////////
	            //Output the XML
	
	            //set up a transformer
	            TransformerFactory transfac = TransformerFactory.newInstance();
	            Transformer trans = transfac.newTransformer();
	            trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
	            trans.setOutputProperty(OutputKeys.INDENT, "yes");
	
	            //create string from xml tree
	            StringWriter sw = new StringWriter();
	            StreamResult result = new StreamResult(sw);
	            DOMSource source = new DOMSource(doc);
	            trans.transform(source, result);
	            String xmlString = sw.toString();
	    		
	            //Finally - write to the file the node "reminders"
    			FileWriter fStream = new FileWriter(filePath);
    			BufferedWriter out = new BufferedWriter(fStream);
	    		out.write(xmlString);
	    		
	    		//close the file
	    		out.close();
	    		
    		}//end of "if"

        }//end of try block
        catch (Exception e) {//catch any exception
            System.out.println(e);
        }
        
    }//end of method 'createRemindersXMLFile'
	
	
	
	
	
	/***********************************************************************************
	 * MethodName: writeNewRegularAlarmToFile
	 * Receives: AlarmFeatures element - object with features of alarm
	 * MoreAbout: This method writes the new alarm features to the file reminders.xml
	 **********************************************************************************/
	public static void writeNewRegularAlarmToFile (AlarmFeatures alarmFeatures, String filePath) {
		
	    try {
	
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

            doc.normalize();
                   
            //Get the root of document (reminders node)
            Element remindersNode = doc.getDocumentElement();

            //create new node for the new alarm
            Element newAlarmNode = doc.createElement("alarm");
            
            //alarm-id
            Element alarmIndex = doc.createElement("index");
            alarmIndex.setTextContent(alarmFeatures.getIndex());
            newAlarmNode.appendChild(alarmIndex);
            
            
            //on/off
            Element status = doc.createElement("status");
            status.setTextContent(alarmFeatures.getStatus());
            newAlarmNode.appendChild(status);
             
            
            //create sub-nodes for newAlarmNode: type, hour, minute, label, days
            Element type = doc.createElement("type");
            
            //if the alarm is smart alarm, then we need to append destination, origin and tto children to type node
            if(alarmFeatures.getSortOfAlarm().equals("Smart")) {
            	
            	Element value = doc.createElement("value");
            	value.setTextContent("Smart");
            	type.appendChild(value);
            	
            	//Append 'origin' node to 'type' node
            	Element origin = doc.createElement("origin");
            	origin.setTextContent(((SmartAlarmFeatures)alarmFeatures).getOrigin());
            	type.appendChild(origin);
            	
            	//Append 'destination' node to 'type' node
            	Element destination = doc.createElement("destination");
            	destination.setTextContent(((SmartAlarmFeatures)alarmFeatures).getDest());
            	type.appendChild(destination);
            	
            	//Append 'time to organize' node to 'type' node
            	Element tto = doc.createElement("tto");
            	tto.setTextContent(((SmartAlarmFeatures)alarmFeatures).getTTO());
            	type.appendChild(tto);           	
            	
            	
            	//Append 'origin' node to 'type' node
            	Element transport = doc.createElement("transport");
            	transport.setTextContent(((SmartAlarmFeatures)alarmFeatures).getTransport());
            	type.appendChild(transport);
            	
            	
            	////////////////////////////////////////////////////////////
            	
            	
            	Element arrivalHour = doc.createElement("arrivalHour");
            	arrivalHour.setTextContent(((SmartAlarmFeatures)alarmFeatures).getArrivalHour());
            	type.appendChild(arrivalHour);
            
            	Element arrivalMinute = doc.createElement("arrivalMinute");
            	arrivalMinute.setTextContent(((SmartAlarmFeatures)alarmFeatures).getArrivalMinute());
            	type.appendChild(arrivalMinute);
            	
  //***************************************************************************************************//          	
            	if(transport.getTextContent().equals("Transit"))
            	{
            	
            		Element distance = doc.createElement("distance");
            		distance.setTextContent(((SmartAlarmFeatures)alarmFeatures).getDistance());
            		type.appendChild(distance);
            		
            		Element duration = doc.createElement("duration");
            		duration.setTextContent(((SmartAlarmFeatures)alarmFeatures).getDuration());
            		type.appendChild(duration);
            		
            		Element track = doc.createElement("track");
            		track.setTextContent(((SmartAlarmFeatures)alarmFeatures).getTrack().toString());
            		type.appendChild(track);
            		
            		
            	
            	}
            	
            }
            else if(alarmFeatures.getSortOfAlarm().equals("Regular")){//Regular alarm 
            	
            	//create only value node and append it of type node
            	Element value = doc.createElement("value");
            	value.setTextContent("Regular");
            	type.appendChild(value);
            }
            else {
            	
            	Element value = doc.createElement("value");
            	value.setTextContent("Quick");
            	type.appendChild(value);
            	
            	//time interval for quick nap
            	Element interval = doc.createElement("interval");
            	interval.setTextContent(alarmFeatures.getQuickInterval());
            	type.appendChild(interval);
            }
            	
            //append 'type' node to 'newAlarmNode' node
            newAlarmNode.appendChild(type);
            
            //append hour node
            Element hour = doc.createElement("hour");
            hour.setTextContent(alarmFeatures.getHour());
            newAlarmNode.appendChild(hour);
            
            //append minute node
            Element minute = doc.createElement("minute");
            minute.setTextContent(alarmFeatures.getMinute());
            newAlarmNode.appendChild(minute);
            
            //append label node
            Element label = doc.createElement("label");
            label.setTextContent(alarmFeatures.getLabel());
            newAlarmNode.appendChild(label);
            
            //append daysToRepeat node
            Element daysToRepeat = doc.createElement("days");
            daysToRepeat.setTextContent(alarmFeatures.getDaysToRepeat());
            newAlarmNode.appendChild(daysToRepeat);         
            
            //id for each day the alarm is on
            Element daysID = doc.createElement("daysID");
            daysID.setTextContent(alarmFeatures.getDaysIDS());
            newAlarmNode.appendChild(daysID);
            
            //snooze interval
            Element snoozeInterval = doc.createElement("snoozeInterval");
            snoozeInterval.setTextContent(alarmFeatures.getSnoozeInterval());
            newAlarmNode.appendChild(snoozeInterval);      
            
            //snooze repeat
            Element snoozeRepeat = doc.createElement("snoozeRepeat");
            snoozeRepeat.setTextContent(alarmFeatures.getSnoozeRepeat());
            newAlarmNode.appendChild(snoozeRepeat);  
            
            //vibration
            Element vib = doc.createElement("vibration");
            vib.setTextContent(alarmFeatures.getVibration());
            newAlarmNode.appendChild(vib);
            
            //tune
            Element tune = doc.createElement("tune");
            tune.setTextContent(alarmFeatures.getTune());
            newAlarmNode.appendChild(tune);                
            
            //volume
            Element volume = doc.createElement("volume");
            volume.setTextContent(alarmFeatures.getVolume());
            newAlarmNode.appendChild(volume);           
            
            //snoozeID
            Element snoozeID = doc.createElement("snoozeID");
            snoozeID.setTextContent("None");
            newAlarmNode.appendChild(snoozeID);
            
            Element id = doc.createElement("id");
            id.setTextContent(alarmFeatures.getID());
            newAlarmNode.appendChild(id);
            
            
            //Append the newAlarmNode to the remindersNode
            if(!remindersNode.hasChildNodes())//if there are no existing alarms - add the first alarm
            	remindersNode.appendChild(newAlarmNode);
            else { //Else - if there are existing alarms in the file - add this alarm as the first alarm in list
            	Node firstAlarm = remindersNode.getChildNodes().item(1);
            	remindersNode.insertBefore(newAlarmNode, firstAlarm);
            }
            
            ////////////
            //SET THE POSITION OF THE NODES
            
            //get list of alarm-nodes
            NodeList alarmNodes = remindersNode.getChildNodes();
            
            //In this loop we get all alarm nodes in the file
            for(int i = 2; i < alarmNodes.getLength() ; i++){

            	//if the current item is instance of Element node
            	if (alarmNodes.item(i) instanceof Element) {
            		
            		//get current alarm node
                    Node currentAlarmNode = alarmNodes.item(i);
                  
                    //get the features list
                    NodeList currentAlarmFeatures = currentAlarmNode.getChildNodes();
                    
                    int indexOfAlarm = Integer.valueOf(currentAlarmFeatures.item(1).getTextContent());
                    indexOfAlarm+=1;
                    currentAlarmFeatures.item(1).setTextContent(Integer.toString(indexOfAlarm));
            		
            	}
            }
            
            
            /////////////////
            //Change reminders.xml file 
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
    		Transformer transformer = transformerFactory.newTransformer();
    		
    		//set the alignment of xml while writing to file
    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
    		
    		DOMSource source = new DOMSource(doc);
    		StreamResult result = new StreamResult(new File(filePath));
    		transformer.transform(source, result);   
            
        }catch (Exception err) {//Catch any Exception
        	err.printStackTrace();
        }
	
	}//end of method 'writeNewRegularAlarmToFile'
	
	
	//
	public static String getSnoozeAlarmSign (String alarmID, String filePath) {
		
		String snoozeID = "None";
		
		
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

  
            //Get the root of document (reminders node)
            Element remindersNode = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            //get list of alarm-nodes
            NodeList alarmNodes = remindersNode.getChildNodes();
            
            //In this loop we get all alarm nodes in the file
            for(int i = 0; i < alarmNodes.getLength() ; i++){

            	//if the current item is instance of Element node
            	if (alarmNodes.item(i) instanceof Element) {
            		
            		
            		//get current alarm node
                    Node currentAlarmNode = alarmNodes.item(i);
                  
                    //get the features list
                    NodeList currentAlarmFeatures = currentAlarmNode.getChildNodes();
                    
                    
                    if(currentAlarmFeatures.item(29).getTextContent().equals(alarmID)) {
                    	snoozeID =  currentAlarmFeatures.item(27).getTextContent();
                        break;
                    }
            	}
            	
            }
            
        }catch (Exception err) {//Catch any Exception
        	err.printStackTrace();
        }
		
		return snoozeID;
	}	
	
	//change snooze ID if there is any snooze ON right now
	public static void changeSnoozeSign (String alarmID, String filePath, String snoozeID) {
		
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

  
            //Get the root of document (reminders node)
            Element remindersNode = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            //get list of alarm-nodes
            NodeList alarmNodes = remindersNode.getChildNodes();
            
            //In this loop we get all alarm nodes in the file
            for(int i = 0; i < alarmNodes.getLength() ; i++){

            	//if the current item is instance of Element node
            	if (alarmNodes.item(i) instanceof Element) {
            		
            		
            		//get current alarm node
                    Node currentAlarmNode = alarmNodes.item(i);
                  
                    //get the features list
                    NodeList currentAlarmFeatures = currentAlarmNode.getChildNodes();
                    
                    
                    if(currentAlarmFeatures.item(29).getTextContent().equals(alarmID)) {
                        currentAlarmFeatures.item(27).setTextContent(snoozeID);
                        break;
                    }
            	}
            	
            }


            /////////////////
            //Update reminders.xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
    		Transformer transformer = transformerFactory.newTransformer();
    		
    		//set the alignment of xml while writing to file
    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
    		
    		
    		DOMSource source = new DOMSource(doc);
    		StreamResult result = new StreamResult(new File(filePath));
    		transformer.transform(source, result);
    		

        }catch (Exception err) {//Catch any Exception
        	err.printStackTrace();
        }
	}
	

	/***********************************************************************************
	 * MethodName: getAllAlarms
	 * Receives: ArrayList<AlarmFeatures> object - array of alarms-features
	 * MoreAbout: This method returns all alarms that exists in file.
	 **********************************************************************************/
	public static ArrayList<AlarmFeatures> getAllAlarms(String filePath){
		
		//create array-list of alarms
		ArrayList<AlarmFeatures> alarms = new ArrayList<AlarmFeatures>();
		
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

  
            //Get the root of document (reminders node)
            Element remindersNode = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            //get list of alarm-nodes
            NodeList alarmNodes = remindersNode.getChildNodes();
            
            //In this loop we get all alarm nodes in the file
            for(int i = 0; i < alarmNodes.getLength() ; i++){

            	//if the current item is instance of Element node
            	if (alarmNodes.item(i) instanceof Element) {
            		
            		
            		//get current alarm node
                    Node currentAlarmNode = alarmNodes.item(i);
                  
                    //get the features list
                    NodeList currentAlarmFeatures = currentAlarmNode.getChildNodes();
                    
                    
                    
                    //get type of alarm
                    Node typeNode = currentAlarmFeatures.item(5);
                    
                    
                    String type = typeNode.getChildNodes().item(1).getTextContent();
                    String origin = null;
                    String dest = null;
                    String tto = null;
                    String transport = null;
                    String arrivalHour = null;
                    String arrivalMinute = null;
                    
                    String distance = null;
                    String duration = null;
                    String track = null;
                    	
                    AlarmFeatures af = null;
                    
                    if(type.equals("Smart")){
                    	
                    	//Get the relevant nodes
                    	origin = typeNode.getChildNodes().item(3).getTextContent();
                    	dest = typeNode.getChildNodes().item(5).getTextContent();
                    	tto = typeNode.getChildNodes().item(7).getTextContent();
                    	transport = typeNode.getChildNodes().item(9).getTextContent();
                    	arrivalHour = typeNode.getChildNodes().item(11).getTextContent();
                    	arrivalMinute = typeNode.getChildNodes().item(13).getTextContent();
                    	
                    	af = new SmartAlarmFeatures();
                    	((SmartAlarmFeatures)af).setOrigin(origin);
                    	((SmartAlarmFeatures)af).setDest(dest);
                    	((SmartAlarmFeatures)af).setTTO(tto);
                    	((SmartAlarmFeatures)af).setTransport(transport);
                    	((SmartAlarmFeatures)af).setArrivalHour(arrivalHour);
                    	((SmartAlarmFeatures)af).setArrivalMinute(arrivalMinute);
                    	
                    	if(transport.equals("Transit"))
                    	{

                        	distance = typeNode.getChildNodes().item(15).getTextContent();
                        	duration = typeNode.getChildNodes().item(17).getTextContent();
                        	track = typeNode.getChildNodes().item(19).getTextContent();
                        	
                        	((SmartAlarmFeatures)af).setDistance(distance);
                        	((SmartAlarmFeatures)af).setDuration(duration);
                        	//setTrack- create Track from this string track!!!!
                        	((SmartAlarmFeatures)af).setTrack(track);
                        	
                        	
                    		
                    	}
                    }
                    else if(type.equals("Quick")) {
                    	
                    	af = new AlarmFeatures();
                    	af.setQuickInterval(typeNode.getChildNodes().item(3).getTextContent());
                    }
                    else
                    	af = new AlarmFeatures();
                    
                    
                    //get the text content from the current alarm features in file
                    String index = currentAlarmFeatures.item(1).getTextContent();
                    String status = currentAlarmFeatures.item(3).getTextContent();
                    String hour = currentAlarmFeatures.item(7).getTextContent();
                    String minute = currentAlarmFeatures.item(9).getTextContent();
                    String label = currentAlarmFeatures.item(11).getTextContent();
                    String days = currentAlarmFeatures.item(13).getTextContent();
                    String daysIDS = currentAlarmFeatures.item(15).getTextContent();
                    String snoozeInterval = currentAlarmFeatures.item(17).getTextContent();
                    String snoozeRepeat = currentAlarmFeatures.item(19).getTextContent();
                    String vibration = currentAlarmFeatures.item(21).getTextContent();
                    String tune = currentAlarmFeatures.item(23).getTextContent();
                    String volume = currentAlarmFeatures.item(25).getTextContent();
                    String id = currentAlarmFeatures.item(29).getTextContent();
                    //Create AlarmFeature object and set the features inside it
                    
                    
                    af.setSortOfAlarm(type);
                    af.setHour(hour);
                    af.setMinute(minute);
                    af.setLabel(label);
                    af.setDaysToRepeat(days);
                    af.setIndex(index);
                    af.setStatus(status);
                    af.setDaysIDS(daysIDS);
                    af.setSnoozeInterval(snoozeInterval);
                    af.setSnoozeRepeat(snoozeRepeat);
                    af.setTune(tune);
                    af.setVibration(vibration);
                    af.setVolume(volume);
                    af.setID(id);
                    
                    
                    //add the AlarmFeatures object to the arrayList
                    alarms.add(af);

            	}
 
            }//end of for loop with s var

        }catch (Exception err) {//Catch any Exception
        	err.printStackTrace();
        }
		
		//return the array of alarms
		return alarms;
		
	}//end of method 'getAllAlarms'
	
	

	///////////////////
	//Change an existing alarm status from off to on and opposite
	public static void changeAlarmStatus(String filePath, String index, String alarmStatus) {
	
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

  
            //Get the root of document (reminders node)
            Element remindersNode = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            //get list of alarm-nodes
            NodeList alarmNodes = remindersNode.getChildNodes();
            

            //if the current item is instance of Element node
            if (alarmNodes.item(2*Integer.valueOf(index)+1) instanceof Element) {
            		
            		
        		//get current alarm node
                Node currentAlarmNode = alarmNodes.item(2*Integer.valueOf(index)+1);
              
                //get the features list
                NodeList currentAlarmFeatures = currentAlarmNode.getChildNodes();	
                
                //Set the sataus of the alarm to the one
                currentAlarmFeatures.item(3).setTextContent(alarmStatus);
                
        	}
            
            /////////////////
            //Update reminders.xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
    		Transformer transformer = transformerFactory.newTransformer();
    		
    		//set the alignment of xml while writing to file
    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
    		
    		
    		DOMSource source = new DOMSource(doc);
    		StreamResult result = new StreamResult(new File(filePath));
    		transformer.transform(source, result);
    		

        }catch (Exception err) {//Catch any Exception
        	err.printStackTrace();
        }
		
	}//end of method 'changeAlarmStatus'
	
	public static AlarmFeatures getAlarm(String alarmID, String filePath) {
		
		AlarmFeatures af = null;
		
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

  
            Element remindersNode = doc.getDocumentElement();
            
            NodeList alarmNodes = remindersNode.getChildNodes();
            
            //In this loop we get all alarm nodes in the file
            for(int i = 0; i < alarmNodes.getLength() ; i++){
            	if (alarmNodes.item(i) instanceof Element) {
            		
            		
            		//get current alarm node
                    Node currentAlarmNode = alarmNodes.item(i);
                  
                    //get the features list
                    NodeList currentAlarmFeatures = currentAlarmNode.getChildNodes();
                    
                    //If the current alarm id is the given ID change it's status
                    if(currentAlarmFeatures.item(29).getTextContent().equals(alarmID)) {
                        
                        //get type of alarm
                        Node typeNode = currentAlarmFeatures.item(5);
                        
                        
                        String type = typeNode.getChildNodes().item(1).getTextContent();
                        String origin = null;
                        String dest = null;
                        String tto = null;
                        String transport = null;
                        String arrivalHour = null;
                        String arrivalMinute = null;
                        
                        String distance = null;
                        String duration = null;
                        String track = null;

                        if(type.equals("Smart")){
                        	
                        	//Get the relevant nodes
                        	origin = typeNode.getChildNodes().item(3).getTextContent();
                        	dest = typeNode.getChildNodes().item(5).getTextContent();
                        	tto = typeNode.getChildNodes().item(7).getTextContent();
                        	transport = typeNode.getChildNodes().item(9).getTextContent();
                        	arrivalHour = typeNode.getChildNodes().item(11).getTextContent();
                        	arrivalMinute = typeNode.getChildNodes().item(13).getTextContent();
                        	
                        	af = new SmartAlarmFeatures();
                        	((SmartAlarmFeatures)af).setOrigin(origin);
                        	((SmartAlarmFeatures)af).setDest(dest);
                        	((SmartAlarmFeatures)af).setTTO(tto);
                        	((SmartAlarmFeatures)af).setTransport(transport);
                        	((SmartAlarmFeatures)af).setArrivalHour(arrivalHour);
                        	((SmartAlarmFeatures)af).setArrivalMinute(arrivalMinute);
                        	
                        	if(transport.equals("Transit"))
                        	{

                            	distance = typeNode.getChildNodes().item(15).getTextContent();
                            	duration = typeNode.getChildNodes().item(17).getTextContent();
                            	track = typeNode.getChildNodes().item(19).getTextContent();
                            	
                            	((SmartAlarmFeatures)af).setDistance(distance);
                            	((SmartAlarmFeatures)af).setDuration(duration);
                            	//setTrack- create Track from this string track!!!!
                            	((SmartAlarmFeatures)af).setTrack(track);
                            	
                            	
                        		
                        	}
                        }
                        else if(type.equals("Quick")) {
                        	
                        	af = new AlarmFeatures();
                        	af.setQuickInterval(typeNode.getChildNodes().item(3).getTextContent());
                        }
                        else
                        	af = new AlarmFeatures();
                        
                        
                        //get the text content from the current alarm features in file
                        String index = currentAlarmFeatures.item(1).getTextContent();
                        String status = currentAlarmFeatures.item(3).getTextContent();
                        String hour = currentAlarmFeatures.item(7).getTextContent();
                        String minute = currentAlarmFeatures.item(9).getTextContent();
                        String label = currentAlarmFeatures.item(11).getTextContent();
                        String days = currentAlarmFeatures.item(13).getTextContent();
                        String daysIDS = currentAlarmFeatures.item(15).getTextContent();
                        String snoozeInterval = currentAlarmFeatures.item(17).getTextContent();
                        String snoozeRepeat = currentAlarmFeatures.item(19).getTextContent();
                        String vibration = currentAlarmFeatures.item(21).getTextContent();
                        String tune = currentAlarmFeatures.item(23).getTextContent();
                        String volume = currentAlarmFeatures.item(25).getTextContent();
                        String id = currentAlarmFeatures.item(29).getTextContent();
                        //Create AlarmFeature object and set the features inside it
                        
                        
                        af.setSortOfAlarm(type);
                        af.setHour(hour);
                        af.setMinute(minute);
                        af.setLabel(label);
                        af.setDaysToRepeat(days);
                        af.setIndex(index);
                        af.setStatus(status);
                        af.setDaysIDS(daysIDS);
                        af.setSnoozeInterval(snoozeInterval);
                        af.setSnoozeRepeat(snoozeRepeat);
                        af.setTune(tune);
                        af.setVibration(vibration);
                        af.setVolume(volume);
                        af.setID(id);
                        
                        break;
                    }
            	}
            	
            }

            /////////////////
            //Update reminders.xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
    		Transformer transformer = transformerFactory.newTransformer();
    		
    		//set the alignment of xml while writing to file
    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
    		
    		
    		DOMSource source = new DOMSource(doc);
    		StreamResult result = new StreamResult(new File(filePath));
    		transformer.transform(source, result);
    		

        }catch (Exception err) {//Catch any Exception
        	err.printStackTrace();
        }
		
		return af;
	}
	
	///////////////////
	//Change an existing alarm status from off to on and change time
	public static void changeTimeAndSetAlarmOn(String filePath, String index, String hour, String minute) {
	
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

  
            //Get the root of document (reminders node)
            Element remindersNode = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            //get list of alarm-nodes
            NodeList alarmNodes = remindersNode.getChildNodes();
            

            //if the current item is instance of Element node
            if (alarmNodes.item(2*Integer.valueOf(index)+1) instanceof Element) {
            		
            		
        		//get current alarm node
                Node currentAlarmNode = alarmNodes.item(2*Integer.valueOf(index)+1);
              
                //get the features list
                NodeList currentAlarmFeatures = currentAlarmNode.getChildNodes();	
                
                //Set the sataus of the alarm to the one
                currentAlarmFeatures.item(3).setTextContent("On");
                currentAlarmFeatures.item(7).setTextContent(hour);
                currentAlarmFeatures.item(9).setTextContent(minute);
                
        	}
            
            /////////////////
            //Update reminders.xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
    		Transformer transformer = transformerFactory.newTransformer();
    		
    		//set the alignment of xml while writing to file
    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
    		
    		
    		DOMSource source = new DOMSource(doc);
    		StreamResult result = new StreamResult(new File(filePath));
    		transformer.transform(source, result);
    		

        }catch (Exception err) {//Catch any Exception
        	err.printStackTrace();
        }
		
	}//end of method 'changeAlarmStatus'
	
	
	//change snooze ID if there is any snooze ON right now
	public static void changeStatusByID (String alarmID, String filePath, String alarmStatus) {
		
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

  
            //Get the root of document (reminders node)
            Element remindersNode = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            //get list of alarm-nodes
            NodeList alarmNodes = remindersNode.getChildNodes();
            
            //In this loop we get all alarm nodes in the file
            for(int i = 0; i < alarmNodes.getLength() ; i++){

            	//if the current item is instance of Element node
            	if (alarmNodes.item(i) instanceof Element) {
            		
            		
            		//get current alarm node
                    Node currentAlarmNode = alarmNodes.item(i);
                  
                    //get the features list
                    NodeList currentAlarmFeatures = currentAlarmNode.getChildNodes();
                    
                    //If the current alarm id is the given ID change it's status
                    if(currentAlarmFeatures.item(29).getTextContent().equals(alarmID)) {
                		
                        //Set the status of the alarm to the one
                        currentAlarmFeatures.item(3).setTextContent(alarmStatus);
                        break;
                    }
            	}
            	
            }


            /////////////////
            //Update reminders.xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
    		Transformer transformer = transformerFactory.newTransformer();
    		
    		//set the alignment of xml while writing to file
    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
    		
    		
    		DOMSource source = new DOMSource(doc);
    		StreamResult result = new StreamResult(new File(filePath));
    		transformer.transform(source, result);
    		

        }catch (Exception err) {//Catch any Exception
        	err.printStackTrace();
        }
	}
	
	//return IDS of alarm
	public static String getDaysIDS (String alarmID, String filePath) {
			
		String alarmDayIDS = null;
		
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

  
            //Get the root of document (reminders node)
            Element remindersNode = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            //get list of alarm-nodes
            NodeList alarmNodes = remindersNode.getChildNodes();
            
            //In this loop we get all alarm nodes in the file
            for(int i = 0; i < alarmNodes.getLength() ; i++){

            	//if the current item is instance of Element node
            	if (alarmNodes.item(i) instanceof Element) {
            		
            		
            		//get current alarm node
                    Node currentAlarmNode = alarmNodes.item(i);
                  
                    //get the features list
                    NodeList currentAlarmFeatures = currentAlarmNode.getChildNodes();
                    
                    //If the current alarm id is the given ID change it's status
                    if(currentAlarmFeatures.item(29).getTextContent().equals(alarmID)) {
                		
                        //Set the status of the alarm to the one
                        alarmDayIDS = currentAlarmFeatures.item(15).getTextContent();
                        break;
                    }
            	}
            	
            }


            /////////////////
            //Update reminders.xml file
            TransformerFactory transformerFactory = TransformerFactory.newInstance();
    		Transformer transformer = transformerFactory.newTransformer();
    		
    		//set the alignment of xml while writing to file
    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
    		
    		
    		DOMSource source = new DOMSource(doc);
    		StreamResult result = new StreamResult(new File(filePath));
    		transformer.transform(source, result);
    		

        }catch (Exception err) {//Catch any Exception
        	err.printStackTrace();
        }
		
		return alarmDayIDS;
	}
	
	
	
	
	/////////////////
	//Delete an existing alarm from reminders.xml
	public static void deleteAlarm(String filePath, String index){
		
		int indexOfAlarm = 0;
		
		try {
			
    		//We Need Doc element to hold the content of the xml file
            DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = docBuilderFactory.newDocumentBuilder();
            Document doc = docBuilder.parse (new File(filePath));

  
            //Get the root of document (reminders node)
            Element remindersNode = doc.getDocumentElement();
            
            //System.out.println(remindersNode.getNodeName());

            //get list of alarm-nodes
            NodeList alarmNodes = remindersNode.getChildNodes();
            
            //if the current item is instance of Element node
            if (alarmNodes.item(2*Integer.valueOf(index)+1) instanceof Element) {
            		
            		
        		//get current alarm node
                Element currentAlarmNode = (Element)alarmNodes.item(2*Integer.valueOf(index)+1);
              
                //remove this node
                currentAlarmNode.getParentNode().removeChild(currentAlarmNode);

                //normalize the document
                doc.normalize();
                
                
                //get list of remaining alarm-nodes
                alarmNodes = remindersNode.getChildNodes();
                
                //In this loop we get all alarm nodes in the file
                for(int i = 0; i < alarmNodes.getLength() ; i++){

                	//if the current item is instance of Element node
                	if (alarmNodes.item(i) instanceof Element) {
                		
                		//get current alarm node
                        currentAlarmNode = (Element)alarmNodes.item(i);
                      
                        //get the features list
                        NodeList currentAlarmFeatures = currentAlarmNode.getChildNodes();

                        currentAlarmFeatures.item(1).setTextContent(Integer.toString(indexOfAlarm));
                        
                        indexOfAlarm+=1;
                		
                	}
                }
            }
            
            if(indexOfAlarm == 0)
            	initializeRemindersFile(filePath);
            else {
	            /////////////////
	            //Update reminders.xml file
	            TransformerFactory transformerFactory = TransformerFactory.newInstance();
	    		Transformer transformer = transformerFactory.newTransformer();
	    		
	    		//set the alignment of xml while writing to file
	    		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");//"\n" at every ending of code line
	    		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
	    		transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");//align with tabs
	    		
	    		
	    		DOMSource source = new DOMSource(doc);
	    		StreamResult result = new StreamResult(new File(filePath));
	    		transformer.transform(source, result);
            }
		}
		catch (Exception err) {//Catch any Exception
	    	err.printStackTrace();
	    }
    }//end of method 'deleteAlarm'
	
	
	public static void initializeRemindersFile(String filePath){
		
		try{
			
	
	    	File previousFile = new File(filePath);
	    	previousFile.delete();
			
	    	//We need a Document
	    	DocumentBuilderFactory dbFactoryNew = DocumentBuilderFactory.newInstance();
	    	DocumentBuilder docBuilderNew = dbFactoryNew.newDocumentBuilder();
	        Document docNew = docBuilderNew.newDocument();
	    	
	    	
	        File newFile = new File(filePath);
	        if(newFile.createNewFile()) {
		        	
		 
		    	//We need a Document
		
		        ////////////////////////
		        //Creating the XML tree
		        
		    	docNew.normalize();
		
		        //create the root element named Reminders and add it to the document
		        Element root = docNew.createElement("reminders");
		        docNew.appendChild(root);
		
		        /////////////////
		        //Output the XML
		
		        //set up a transformer
		        TransformerFactory transfac = TransformerFactory.newInstance();
		        Transformer trans = transfac.newTransformer();
		        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		        trans.setOutputProperty(OutputKeys.INDENT, "yes");
		
		        //create string from xml tree
		        StringWriter sw = new StringWriter();
		        StreamResult result = new StreamResult(sw);
		        DOMSource source = new DOMSource(docNew);
		        trans.transform(source, result);
		        String xmlString = sw.toString();
				
		        //Finally - write to the file the node "reminders"
				FileWriter fStream = new FileWriter(filePath);
				BufferedWriter out = new BufferedWriter(fStream);
				out.write(xmlString);
				
				//close the file
				out.close();	
	        }
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
			
}//EOF
